define(['require' , 'exports' , 'module' , 'jquery' , 'layer' , 'common/common' , 'baiduTemplate'] , function (require , exports , module , $ , layer , common) {

    var alertAddAddressHtml = function () {
        $('.new-build-address').bind('click' , function () {
            window.location.href = "/user/address-add";
        });
    };

    var alertEditAddressHtml = function () {
        $('.address-edit').bind('click' , function (e) {
            e.stopPropagation();
            var aid = $(this).attr('id');
            window.location.href = "/user/address-update/" + aid;
        });
    };

    var getProvince = function (selectId) {
        $.ajax({
            'url'       : '/area?pid=0&level=province',
            'type'      : 'GET',
            'dataType'  : 'JSON',
            'success'   : function (data) {
                if(data.code == 0){
                    var html = '<option id="0">选择省份</option>';
                    for (var area of data.data){
                        if(selectId == area.id || selectId == area.name) {
                            html += '<option selected="true" value="' + area.id + '">' + area.name + '</option>';
                        }else {
                            html += '<option value="' + area.id + '">' + area.name + '</option>';
                        }
                    }
                    $('#province').html(html);
                }
            },
            'error'     : function (error) {
                layer.open({
                    content : '服务器链接错误' ,
                    skin : 'msg' ,
                    time : 2
                });
            }
        });
    };

    var getCity = function () {
        $('#province').bind('change' , function () {
            var pid = $(this).val();
            cityInit(pid);
        });
    };

    var getDistrict = function () {
        $('#city').bind('change' , function () {
            var pid = $(this).val();
            districtInit(pid);
        });
    };

    var cityInit = function (pid , selectId) {

        $.ajax({
            'url'       : '/area?pid='+ pid +'&level=city',
            'type'      : 'GET',
            'dataType'  : 'JSON',
            'success'   : function (data) {
                if(data.code == 0){
                    var html = '<option id="0">选择城市</option>';
                    for (var area of data.data){
                        if(selectId == area.id || selectId == area.name) {
                            html += '<option selected="true" value="' + area.id + '">' + area.name + '</option>';
                        }else {
                            html += '<option value="' + area.id + '">' + area.name + '</option>';
                        }
                    }
                    $('#city').html(html);
                }
            },
            'error'     : function (error) {
                layer.open({
                    content : '服务器链接错误' ,
                    skin : 'msg' ,
                    time : 2
                });
            }
        });
    };

    var districtInit = function (cid , selectId) {
        $.ajax({
            'url'       : '/area?pid='+ cid +'&level=district',
            'type'      : 'GET',
            'dataType'  : 'JSON',
            'success'   : function (data) {
                if(data.code == 0){
                    var html = '<option id="0">选择区县</option>';
                    for (var area of data.data){
                        if(selectId == area.id || selectId == area.name) {
                            html += '<option selected="true" value="' + area.id + '">' + area.name + '</option>';
                        }else {
                            html += '<option value="' + area.id + '">' + area.name + '</option>';
                        }
                    }
                    $('#district').html(html);
                }
            },
            'error'     : function (error) {
                layer.open({
                    content : '服务器链接错误' ,
                    skin : 'msg' ,
                    time : 2
                });
            }
        });
    };

    var changeSex = function () {
        $('.sex-item').bind('click' , function () {
            $('.sex-item').css({color:'#666'});
            $(this).css({color:'#ea4f55'});
            $('#sex').attr('selectSex' , $(this).attr('id'));
        });
    };
    
    var addAddress = function () {
        $('.build-address').bind('click' , function () {
            var saveData = new Object();
            saveData.name               = $('#name').val();
            saveData.sex                = $('#sex').attr('selectSex');
            saveData.mobile             = $('#mobile').val();
            saveData.province           = $('#province').val();
            saveData.district           = $('#district').val();
            saveData.city               = $('#city').val();
            saveData.address            = $('#address').val();
            saveData.house_number       = $('#house_number').val();
            saveData.lng                = $('#lng').val();
            saveData.lat                = $('#lat').val();

            common.ajaxPost('/user/address-add' , saveData , function (error , data) {
                if(error == null && data.code == 0){
                    window.location.href = '/user/address';
                }else{
                    layer.open({
                        content : data.msg ,
                        skin : 'msg' ,
                        time : 2
                    });
                }
            });
        });  
    };

    var updateAddress = function () {
        $('.update-address').bind('click' , function () {
            var saveData = new Object();
            saveData.name            = $('#name').val();
            saveData.sex             = $('#sex').attr('selectSex');
            saveData.mobile          = $('#mobile').val();
            saveData.province        = $('#province').val();
            saveData.city            = $('#city').val();
            saveData.district        = $('#district').val();
            saveData.address         = $('#address').val();
            saveData.house_number    = $('#house_number').val();
            saveData.id              = $('#aid').val();
            saveData.lng             = $('#lng').val();
            saveData.lat             = $('#lat').val();

            common.ajaxPost('/user/address-update' , saveData , function (error , data) {
                if(error == null && data.code == 0){
                    window.location.href = '/user/address';
                }else{
                    layer.open({
                        content : '修改失败' ,
                        skin : 'msg' ,
                        time : 2
                    });
                }
            });
        });
    };

    var amap = function (type) {
        require(['amap'], function() {
            window.init = function() {
                require(['libs/initMap'], function(mapIniter) {
                    if(type == 'index') {
                        var lnglat = common.getLngLat();
                        if((lnglat.lng != null || lnglat.lng != undefined) && (lnglat.lat != null || lnglat.lng != undefined)){

                            var showAddress = window.sessionStorage.getItem('address');

                            window.sessionStorage.setItem('goodspage' , 1);

                            document.getElementById('amap-address').innerHTML = showAddress;

                            require(['app/index'], function (index) {
                                index.dropload();
                                index.getNavList();
                            })
                        }else {
                            layer.open({
                                type: 2
                                ,content: '定位中'
                            });
                            mapIniter.init(__setIndexAddress);
                        }
                    }else if(type == 'address'){
                        mapIniter.init(__setAddress);
                    }
                })
            }
        });
    };

    var __setAddress = function (data) {
        var Lng = data.position.getLng();
        var Lat = data.position.getLat();

        var province            = data.addressComponent.province;
        var city                = data.addressComponent.city;
        var district            = data.addressComponent.district;
        var township            = data.addressComponent.township;

        var adcode              = data.addressComponent.adcode;

        getProvince(province);
        cityInit(adcode , city);
        districtInit(adcode , district);

        document.getElementById('lng').value = Lng;
        document.getElementById('lat').value = Lat;

        var sliceLength = province.length+city.length+district.length+township.length;
        var address = data.formattedAddress.slice(sliceLength);

        document.getElementById('address').value = address;
    };

    var __setIndexAddress = function (data) {
        var Lng = data.position.getLng();
        var Lat = data.position.getLat();

        common.setLngLat(Lng , Lat);

        if(data.addressComponent != undefined) {
            var province = data.addressComponent.province;
            var city = data.addressComponent.city;
            var district = data.addressComponent.district;
            var township = data.addressComponent.township;

            var sliceLength = province.length + city.length + district.length + township.length;
            var showAddress = data.formattedAddress.slice(sliceLength);

            document.getElementById('amap-address').innerHTML = showAddress;
            window.sessionStorage.setItem('address' , showAddress);

            require(['app/index'], function (index) {
                index.dropload();
                index.getNavList();
            })
        }else{
            //提示
            layer.open({
                content: '定位出错啦,请刷新重试'
                ,skin: 'msg'
                ,time: 2 //2秒后自动关闭
            });
        }

        layer.closeAll();
    };

    var selectAddress = function () {

        require(['amap'], function() {
            require(['libs/initMap'], function(mapIniter) {
                mapIniter.searchPoi();
            });
        });
    };

    var useAddress = function () {
        $('.use-address').bind('click' , function () {
            var __this = $(this);
            var lng = __this.attr('lng');
            var lat = __this.attr('lat');
            var address = __this.attr('address');
            var id = __this.attr('id');

            $.ajax({
                'url'       : '/user/address/use/' + id,
                'type'      : 'GET',
                'dataType'  : 'JSON',
                'success'   : function (data) {
                    if(data.code == 0){
                        window.sessionStorage.setItem('address' , address);
                        common.setLngLat(lng , lat);
                        var refer = document.referrer;
                        window.location.href = refer;
                    }
                },
                'error'     : function (error) {
                    layer.open({
                        content : '操作失败,请重新选择' ,
                        skin : 'msg' ,
                        time : 2
                    });
                }
            });
        });
    };

    exports.useAddress = useAddress;

    exports.selectAddress = selectAddress;

    exports.amap = amap;

    exports.alertAddAddressHtml = alertAddAddressHtml;
    exports.alertEditAddressHtml = alertEditAddressHtml;
    exports.getProvince = getProvince;
    exports.getCity = getCity;
    exports.cityInit = cityInit;
    exports.districtInit = districtInit;
    exports.addAddress = addAddress;
    exports.updateAddress = updateAddress;
    exports.changeSex = changeSex;
});
